package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.Bo.SpuBo;
import com.leyou.item.pojo.*;
import com.leyou.search.Repository.GoodsRepository;
import com.leyou.search.client.BrandClient;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.GoodsClient;
import com.leyou.search.client.SpecClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.pojo.SearchRequest;
import com.leyou.search.pojo.SearchResult;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Log4j2
@Service
public class IndexService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private SpecClient specClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    public Goods buildGoods(SpuBo spuBo) {
        Goods goods = new Goods();
        //查询搜索关键字,标题,分类,名称
        List<String> names = this.categoryClient.queryNameByIds(
                Arrays.asList(spuBo.getCid1(), spuBo.getCid2(), spuBo.getCid3()));
        String name = this.brandClient.queryBrandByBrandId(spuBo.getBrandId());
        String all = spuBo.getTitle() + " " + name + " " + StringUtils.join(names, " ");

        //查询sku信息,取出价格信息和title,id;图片....价格单独存放
        List<Sku> skus = this.goodsClient.querySkuBySpuId(spuBo.getId());
        List<Long> price = new ArrayList<>();
        List<Map<String, Object>> skuList = new ArrayList<>();
        skus.forEach(sku -> {
            price.add(sku.getPrice());
            Map<String, Object> map = new HashMap<>();
            //json对象格式;并且只需要四个信息
            map.put("id", sku.getId());
            map.put("title", sku.getTitle());
            map.put("price", sku.getPrice());
            map.put("image", StringUtils.isBlank(
                    sku.getImages()) ? " " : sku.getImages().split(",")[0]);
            skuList.add(map);
        });

        //查询规格参数信息:key在规格参数里;值在spudetail里;
        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuBo.getId());
        List<SpecParam> params = this.specClient.querySpecParam(null, spuBo.getCid3(), true,null);
        //思路:把规格参数的id和规格参数的值一一对应到展现出来,全局和特有
        //先把参数值放到map 中;在一次取出来,重新组合,返回前端
        Map<Long, String> generic = JsonUtils.parseMap(spuDetail.getGenericSpec(), Long.class, String.class);
        Map<Long, List<String>> special = JsonUtils.nativeRead(spuDetail.getSpecialSpec(),
                new TypeReference<Map<Long, List<String>>>() {
                });
        Map<String, Object> spec = new HashMap<>();

        for (SpecParam param : params) {
            Object value = null;
            if (param.getGeneric()) {//判断是不是全局属性
                value = generic.get(param.getId());

                //数值类型需要加分段
                if (param.getNumeric()) {
                    value = this.chooseSegment(value.toString(), param);
                }
            } else {
                value = special.get(param.getId());
            }
            if (value == null) {
                value = "其他";
            }
            spec.put(param.getName(), value);
        }
        BeanUtils.copyProperties(spuBo, goods);
        goods.setAll(all);// 查询搜索关键字,标题,分类,品牌
        goods.setPrice(price);// 查询价格
        goods.setSkus(JsonUtils.serialize(skuList));// 查询sku信息的json 格式
        goods.setSpecs(spec);// 查询可搜索的规格参数
        return goods;
    }

    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }



}
